package handler

import (
	"encoding/json"
	"share-sys/cache"
	"share-sys/model"
	"share-sys/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
	}

	redis_login_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()

	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "错误三次",
		})
		return
	}

	var user model.User

	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误三次，封禁两小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}

func List(c *gin.Context) {

	var article []model.Article

	redis_list_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取列表成功",
		"data": article,
	})
	return

}
